<?php
/**
 * File: Order.php
 * User: Mr.Yang
 * Date: 2025/4/2 0002
 * Time: 10:18
 * Note:
 */

namespace app\home\controller;


use app\admin\model\Address;
use app\admin\model\Order as OrderModel;
use app\admin\model\Cart as CartModel;
use app\admin\model\OrderLog;
use app\admin\model\User as UserModel;
use app\admin\model\Book as BookModel;
use app\admin\model\OrderInfo;
use app\admin\model\MoneyLog;
use think\Db;

class Order extends Base
{

    /**
     * Note: 支付购买商品
     * User: Mr.Yang
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post('data/a');
            $result = $this->validate($data, 'Order');
            if ($result !== true) {
                $this->error($result);
            }
            if (strtolower($data['captcha']) != session('code')) {
                //$this->error('验证码错误');
            }
            $uid = session('userid');
            $data['cartid'] = explode(',', $data['cartid']);
            list($cart, $total) = $this->getCartAndTotal($uid, $data['cartid']);
            $user = UserModel::where('id', '=', $uid)->findOrFail();
            if ($user['money'] < $total) {
                $this->error('账号余额不足');
            }
            $address = Address::where('id', '=', $data['address_id'])->findOrFail();
            if (!$address) {
                $this->error('收货地址不存在');
            }
            //判断支付密码是否正确
            if (createPassword($data['payword'], $user['paysalt']) != $user['payword']) {
                $this->error('支付密码不正确');
            }
            $orderModel = new OrderModel();
            $flag = false;
            $errmsg = '';
            Db::startTrans();
            try{
                //添加订单
                $orderModel->add([
                    'truename' => $address['truename'],
                    'mobile' => $address['mobile'],
                    'address' => $this->area_pos($address['areaid'], '').$address['address'],
                    'userid' => $uid,
                    'amount' => $total
                ]);
                $order_id = $orderModel->getLastInsID();
                foreach ($cart as $k => $v) {
                    if ($v['total'] < $v['number']) {
                        //库存不足
                        $errmsg = $v['bname'].'库存不足';
                        break;
                    }
                    OrderInfo::create([
                        'order_id' => $order_id,
                        'bookid' => $v['bookid'],
                        'bname' => $v['bname'],
                        'thumb' => $v['thumb'],
                        'price' => $v['price'],
                        'number' => $v['number']
                    ]);
                    BookModel::where('id', '=', $v['bookid'])->setDec('total', $v['number']);
                    BookModel::where('id', '=', $v['bookid'])->setInc('orders', 1);
                }
                //删除购物车商品
                CartModel::where('id', 'in', $data['cartid'])->delete();
                //扣除账号金额
                UserModel::where('id', '=', $uid)->setDec('money', $total);
                MoneyLog::create([
                    'amount' => sprintf('%.2f', $user['money'] - $total),
                    'money' => $total,
                    'status' => 0,
                    'reason' => '订单支付',
                    'note' => '订单号：'.$order_id,
                    'username' => $user['username']
                ]);
                OrderLog::create([
                    'order_id' => $order_id,
                    'title' => '支付下单'
                ]);
                if (!$errmsg) {
                    Db::commit();
                    $flag = true;
                }
            }catch (\Exception $e) {
                Db::rollback();
            }
            if ($flag) {
                $this->success('支付完成，购买成功！');
            }
            $this->error($errmsg ? $errmsg : '购买失败');
        }
    }

    /**
     * Note: 设置订单完成
     * User: Mr.Yang
     */
    public function finish()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->get('id', 0);
            $order = OrderModel::where('id', '=', $id)->find()->toArray();
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order['status'] != 2) {
                $this->error('订单不能完成');
            }
            $res = OrderModel::where('id', '=', $id)->update([
                'status' => 3
            ]);
            if ($res) {
                $this->success('订单已完成');
            }
            $this->error('设置完成失败');
        }
    }

    /**
     * Note: 删除已完成的订单
     * User: Mr.Yang
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->get('id', 0);
            $order = OrderModel::where('id', '=', $id)->find()->toArray();
            if (!$order) {
                $this->error('订单不存在');
            }
            if ($order['status'] != 3) {
                $this->error('订单不能删除');
            }
            Db::startTrans();
            $flag = false;
            try{
                OrderInfo::where('order_id', '=', $id)->delete();
                OrderModel::where('id', '=', $id)->delete();
                Db::commit();
                $flag = true;
            }catch (\Exception $e) {
                Db::rollback();
            }
            if ($flag) {
                
            }
        }
    }
}